﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.Configuration;
using Abp.Localization;
using Abp.Net.Mail;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;


namespace SimpleCmsWithAbp.EntityFrameworkCore.Seed.IdentityServer
{
    public class DefaultClentCreator
    {
        private readonly ConfigurationDbContext _context;

        public DefaultClentCreator(ConfigurationDbContext context)
        {
            _context = context;
        }

        public void Create()
        {
            CreateDefaultClient();
        }

        private void CreateDefaultClient()
        {
            if (_context.Clients.Any()) return;
            foreach (var client in GetClients())
            {
                _context.Clients.Add(client.ToEntity());
            }
            _context.SaveChanges();
        }

        private static IEnumerable<IdentityServer4.Models.Client> GetClients() => new List<IdentityServer4.Models.Client>
            {
                new IdentityServer4.Models.Client
                {
                    ClientId = "client",
                    AllowedGrantTypes =
                    {
                        GrantType.ResourceOwnerPassword,
                        GrantType.ClientCredentials
                    },
                    AllowedScopes = {"default-api"},
                    ClientSecrets =
                    {
                        new IdentityServer4.Models.Secret("secret".Sha256())
                    }
                }
            };
    }
}
